import { set } from "date-fns";
import { useState } from "react";
import clsx from "clsx";
import styles from "./style.module.css";

const handleDecimal = (input, fixed = 2) => {
  if (typeof input === "string" && input.indexOf(".") > -1) {
    const [int, decimal] = input.split(".");
    return int + "." + decimal.slice(0, fixed);
  }
  return input;
};

const NumberField = ({ value = ["", ""], onChange, integer = false }) => {
  const [tipsShow, setTipsShow] = useState(false);
  const [values, setValues] = useState<any[]>(value);

  const handleChange = (val, index) => {
    if (isNaN(Number(val))) return;
    const input =
      val === "" || val === undefined ? val : integer ? Number(val) : val;

    let newValues = [...values];

    newValues[index] = handleDecimal(input);
    setValues(newValues as any);

    if (
      Number(newValues[0]) &&
      Number(newValues[1]) &&
      Number(newValues[0]) > Number(newValues[1])
    ) {
      setTipsShow(true);
      return;
    }

    if (values[0] && values[1]) {
      setTipsShow(false);
      onChange(newValues);
    }
  };

  return (
    <div className="flex flex-col">
      <div className="flex justify-between">
        <input
          className="border-b-1 border-gray-200"
          type={integer ? "tel" : "number"}
          value={values[0] || ''}
          onChange={(e) => handleChange(e.target.value, 0)}
        />
        <span>至</span>
        <input
          className="border-b-1 border-gray-200"
          type={integer ? "tel" : "number"}
          value={values[1] || ''}
          onChange={(e) => handleChange(e.target.value, 1)}
        />
      </div>

      <p
        className={clsx("text-[#f00]", styles.tips, {
          [styles.show]: tipsShow,
          [styles.hide]: !tipsShow,
        })}
      >
        前后数字的大小不匹配
      </p>
    </div>
  );
};

export default NumberField;
